package com.hdu.careerplan.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.careerplan.configuration.FilepathConfiguration;
import com.hdu.careerplan.mapper.ResumeMapper;
import com.hdu.careerplan.mapper.UserBasicInfoMapper;
import com.hdu.careerplan.mapper.UserEducationInfoMapper;
import com.hdu.careerplan.pojo.dto.UserBasicInfoDTO;
import com.hdu.careerplan.pojo.dto.UserEducationInfoDTO;
import com.hdu.careerplan.pojo.entity.Resume;
import com.hdu.careerplan.pojo.entity.User;
import com.hdu.careerplan.pojo.entity.UserBasicInfo;
import com.hdu.careerplan.pojo.entity.UserEducationInfo;
import com.hdu.careerplan.service.UserService;
import com.hdu.careerplan.mapper.UserMapper;
import com.hdu.careerplan.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;

/**
* @author 10240
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-02-16 11:34:33
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService{

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserBasicInfoMapper userBasicInfoMapper;

    @Resource
    private UserEducationInfoMapper userEducationInfoMapper;

    @Resource
    private ResumeMapper resumeMapper;


    @Override
    public int register(String phone, String password) {
        log.info("user register service");
        // 1.校验手机号和密码是否满足要求

        // 2.查找该手机号是否有被注册过
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            return -1;
        }

        // 2. 加密
        User user = new User();
        user.setPassword(PasswordUtil.encryptPassword(password));
        user.setPhone(phone);
        int insertSituation = userMapper.insert(user);
        if (insertSituation == 1) {
            return 0;
        }
        return -1;
    }

    @Override
    public User login(String phone, String password) {
        log.info("user login service");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone).eq("password", PasswordUtil.encryptPassword(password));
        return userMapper.selectOne(queryWrapper);

    }

    @Override
    public int updateBasicInfo(UserBasicInfoDTO userBasicInfoDTO, String phone) {
        UpdateWrapper<UserBasicInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("phone", phone);
        updateWrapper.set("code", userBasicInfoDTO.getCode());
        updateWrapper.set("name", userBasicInfoDTO.getName());
        updateWrapper.set("gender", userBasicInfoDTO.getGender());
        updateWrapper.set("birthday", userBasicInfoDTO.getBirthday());
        updateWrapper.set("email", userBasicInfoDTO.getEmail());
        int update = userBasicInfoMapper.update(null, updateWrapper);
        if (update == 0) {
            return -1;
        }
        return 0;
    }

    @Override
    public UserBasicInfo getBasicInfo(String phone) {
        QueryWrapper<UserBasicInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return userBasicInfoMapper.selectOne(queryWrapper);
    }

    @Override
    public int updateEducationInfo(UserEducationInfoDTO userEducationInfoDTO, String phone) {
        UpdateWrapper<UserEducationInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("phone", phone);
        updateWrapper.set("student_type", userEducationInfoDTO.getStudentType());
        updateWrapper.set("enrollment_date", userEducationInfoDTO.getEnrollmentDate());
        updateWrapper.set("duration", userEducationInfoDTO.getDuration());
        updateWrapper.set("graduation_date", userEducationInfoDTO.getGraduationDate());
        updateWrapper.set("school", userEducationInfoDTO.getSchool());
        updateWrapper.set("college", userEducationInfoDTO.getCollege());
        updateWrapper.set("class_number", userEducationInfoDTO.getClassNumber());
        int update = userEducationInfoMapper.update(null, updateWrapper);
        if (update == 0) {
            return -1;
        }
        return 0;
    }

    @Override
    public UserEducationInfo getEducationInfo(String phone) {
        QueryWrapper<UserEducationInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return userEducationInfoMapper.selectOne(queryWrapper);
    }

    @Override
    public int uploadResume(MultipartFile resumeFile, String formData,  Long userId, String phone) throws IOException {
        log.info("文件上传，路径为：{}", FilepathConfiguration.storageDirPath);
        log.info("{}", userId);
        String originalFilename = resumeFile.getOriginalFilename();

        String extname = null;
        if (originalFilename != null) {
            extname = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        String newFilename = UUID.randomUUID() + extname;
        Resume resume = JSONObject.parseObject(formData, Resume.class);
        resume.setUserId(userId);
        resume.setUuid(newFilename);

        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Resume resumeInDB = resumeMapper.selectOne(queryWrapper);
        if (resumeInDB == null) {
            resumeMapper.insert(resume);
            resumeFile.transferTo(new File(FilepathConfiguration.storageDirPath+ newFilename));
        } else {
            File file = new File(FilepathConfiguration.storageDirPath + resumeInDB.getUuid());
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                }
            }
            UpdateWrapper<Resume> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("uuid", newFilename);
            updateWrapper.eq("user_id", userId);
            resumeMapper.update(resume, updateWrapper);
            resumeFile.transferTo(new File(FilepathConfiguration.storageDirPath+ newFilename));
        }


        return 0;

    }

    @Override
    public Resume getResume(Long userId) {
        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .select("directions","skills","self_evaluation","internships","projects","competitions");
        List<Resume> resumes = resumeMapper.selectList(queryWrapper);
        if (resumes.size() != 1) return null;
        else return resumes.get(0);
    }

    @Override
    public File downloadResume(Long userId) {
        //1. 先查找有没有上传简历
        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Resume> resumes = resumeMapper.selectList(queryWrapper);

        //2. 数据出错1，即失败
        if (resumes.size() != 1) {
            log.info("没有上传简历");
            return null;
        }

        //3. 没有问题，判断文件在不在
        String fileName = resumes.get(0).getUuid();
        String completedFilePath = FilepathConfiguration.storageDirPath + fileName;
        File file = new File(completedFilePath);
        //4. 文件不存在
        if(!file.exists()){
            log.info("简历文件丢失，文件位置：{}", completedFilePath);
            return null;
        }


        return file;


    }

}




